package cn.com.kblog.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.PutObjectResponse;

public class UploadUtils4BOS {
		private static final Log log = LogFactory.getLog(UploadUtils4BOS.class);

	    // ----------------------------------------
		static String HOST = "bj.bcebos.com";
		static String ACCESS_KEY_ID = AppConfigUtil.get("bos.username");
		static String SECRET_ACCESS_KEY =  AppConfigUtil.get("bos.password");
		static String BUCKET = AppConfigUtil.get("bos.bucket");;
		// ----------------------------------------
	    
	    private static BosClient client = null;
	    static{
	    	// 初始化一个BosClient
		    BosClientConfiguration config = new BosClientConfiguration();
		    config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
		    client = new BosClient(config);
		}
	    
	    public static String uploadFile(File file) {
	        String filename = _createFilename(file);
	        // 以文件形式上传Object
	        PutObjectResponse response = client.putObject(BUCKET,"images/"+ filename, file);
	        log.info("etag: " + response.getETag());
	        
	        String url = "http://"+HOST+"/"+BUCKET+"/images/"+filename;
	        return url;
	    }	
	    

		/**
		 * 生成文件唯一文件名
		 * @param file
		 * @return
		 */
		private static String _createFilename(File file) {
			String oldName = file.getName();
			String fileType = oldName.substring(oldName.lastIndexOf("."), oldName.length());
			String newName = System.currentTimeMillis() + fileType;
			return newName;
		}
}
